<?php


namespace App\Http\Controllers\Admin;


use App\Http\Common\BaseController;
use App\Http\Validator\UserValidator;
use App\Imports\CompanyUserImport;
use App\Models\AdminFunctions;
use App\Models\CommunityAward;
use App\Models\CommunityIntroduce;
use App\Models\Grade;
use App\Models\Introduce;
use App\Models\Notice;
use App\Models\Role;
use App\Models\User;
use App\Models\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Excel;


class AdminController extends BaseController
{
    /**
     * 获取社团介绍
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getIntroduce(Request $request){
        $introduce['introduce'] = CommunityIntroduce::first(['id','community_introduce','introduce_image','introduce_update_time']);
        $introduce['introduce']['introduce_update_time'] =  $this->switchPreciseTime( $introduce['introduce']['introduce_update_time'] );
        $introduce['qrcode']=CommunityIntroduce::where('id','>',1)
            ->get(['id','qrcode_update_time','grade_id','president_qrcode']);
        foreach ($introduce['qrcode'] as $qrcode){
            $qrcode['qrcode_update_time'] =  $this->switchPreciseTime($qrcode['qrcode_update_time']);
            $qrcode['grade'] =  Grade::where('id','=',$qrcode['grade_id'])->first(['grade'])['grade'];
        }
        return $this->returnJson(self::SUCCESS,'成功' ,$introduce);
    }

    /**
     * 修改社团介绍
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     *
     */
    public function  updateIntroduce(Request $request){
        $content = $request->input('content');
        $file = $request->file('img');
        $user_id =$request->userId;
        $updateList =array();
        //创建启动事务
        DB::beginTransaction();
        try {
            if ($file){
            //获取文件后缀
            $suffix = $file->getClientOriginalExtension();

            //判断文件后缀
            $rule = ['jpg', 'png', 'gif','jpeg'];
            if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

            //判断文件大小
            $fileSize = $file->getSize();
            if ($fileSize > 10 * 1024 * 1024){
                return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
            }
            $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
            if (!$filename = $this->uploadOss('wdad/introduce/'  , $fileUrl, $file->getRealPath())){
                return $this->returnJson(self::ERROR,'失败');
            }
            $updateList['introduce_image'] = $filename['oss-request-url'];
                $updateList['introduce_update_time'] = time();
            }

            if (isset($content)){
                $updateList['community_introduce'] = $content;
                $updateList['introduce_update_time'] = time();
            }

            CommunityIntroduce::where('id','=',1)->update($updateList);

            $content = $this->mkNoticeContent($user_id,'','社团介绍' ,4);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }


    /**
     * 修改社长二维码
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function  updatePresidentQrcode(Request $request){
        $file = $request->file('img');
        $id = $request->input('id');
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
                //获取文件后缀
                $suffix = $file->getClientOriginalExtension();

                //判断文件后缀
                $rule = ['jpg', 'png', 'gif','jpeg'];
                if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

                //判断文件大小
                $fileSize = $file->getSize();
                if ($fileSize > 10 * 1024 * 1024){
                    return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
                }
                $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
                if (!$filename = $this->uploadOss('wdad/introduce/president_qrcode/'  , $fileUrl, $file->getRealPath())){
                    return $this->returnJson(self::ERROR,'失败');
                }
                CommunityIntroduce::where('id','=',$id)->update([
                    'president_qrcode'=>$filename['oss-request-url'],
                    'qrcode_update_time' => time()
                ]);

            $content = $this->mkNoticeContent($user_id,'','社长二维码' ,4);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    public function  createPresidentQrcode(Request $request){
        $file = $request->file('img');
        $grade_id = $request->input('grade_id');
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
                //获取文件后缀
                $suffix = $file->getClientOriginalExtension();

                //判断文件后缀
                $rule = ['jpg', 'png', 'gif','jpeg'];
                if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

                //判断文件大小
                $fileSize = $file->getSize();
                if ($fileSize > 10 * 1024 * 1024){
                    return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
                }
                $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
                if (!$filename = $this->uploadOss('wdad/introduce/president_qrcode/'  , $fileUrl, $file->getRealPath())){
                    return $this->returnJson(self::ERROR,'失败');
                }
                CommunityIntroduce::insert([
                    'president_qrcode'=>$filename['oss-request-url'],
                    'grade_id'=>$grade_id,
                    'qrcode_update_time' => time()

                ]);

            $content = $this->mkNoticeContent($user_id,'','社长二维码' ,2);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    public function  deletePresidentQrcode(Request $request){
        $id = $request->input('id');
        if ($id==1)      return $this->returnJson(self::FIELD_ERROR,'无此二维码');
        if (CommunityIntroduce::where('id','=',$id)->count()==0){
            return $this->returnJson(self::FIELD_ERROR,'无此二维码');
        }
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
            CommunityIntroduce::where('id','=',$id)->delete();

            $content = $this->mkNoticeContent($user_id,'','社长二维码' ,3);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    public function  deleteAward(Request $request){
        $id = $request->input('id');
        if (CommunityIntroduce::where('id','=',$id)->count()==0){
            return $this->returnJson(self::FIELD_ERROR,'无此奖项');
        }
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
            CommunityAward::where('id','=',$id)->delete();

            $content = $this->mkNoticeContent($user_id,'','获奖荣誉' ,3);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    /**
     * 修改获奖荣誉
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function  updateAward(Request $request){
        $username = $request->input('username');
        $content = $request->input('content');


        $id = $request->input('id');
        if (CommunityAward::where('id','=',$id)->count()==0){
            return $this->returnJson(self::FIELD_ERROR,'无此奖项');
        }
        $updateList =array();
        $file = $request->file('img');
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
            if ($file){
                //获取文件后缀
                $suffix = $file->getClientOriginalExtension();

                //判断文件后缀
                $rule = ['jpg', 'png', 'gif','jpeg'];
                if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

                //判断文件大小
                $fileSize = $file->getSize();
                if ($fileSize > 10 * 1024 * 1024){
                    return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
                }
                $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
                if (!$filename = $this->uploadOss('wdad/introduce/award'  , $fileUrl, $file->getRealPath())){
                    return $this->returnJson(self::ERROR,'失败');
                }
                $updateList['award_img'] = $filename['oss-request-url'];
                $updateList['update_time'] = time();
            }

            if (isset($content)){
                $updateList['award_content'] = $content;
                $updateList['update_time'] = time();
            }
            if (isset($username)){
                $updateList['award_username'] = $username;
                $updateList['update_time'] = time();
            }

            CommunityAward::where('id','=',$id)->update($updateList);
            $content = $this->mkNoticeContent($user_id,'','获奖荣誉' ,4);
            $this->creatNotice(2,$user_id,$content);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    public function  createAward(Request $request){
        $username = $request->input('username');
        $content = $request->input('content');
        $file = $request->file('img');
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
            if ($file){
                //获取文件后缀
                $suffix = $file->getClientOriginalExtension();

                //判断文件后缀
                $rule = ['jpg', 'png', 'gif','jpeg'];
                if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

                //判断文件大小
                $fileSize = $file->getSize();
                if ($fileSize > 10 * 1024 * 1024){
                    return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
                }
                $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
                if (!$filename = $this->uploadOss('wdad/introduce/award'  , $fileUrl, $file->getRealPath())){
                    return $this->returnJson(self::ERROR,'失败');
                }
            }

            CommunityAward::insert([
                'award_username'=>$username,
                'award_content'=>$content,
                'create_time'=>time(),
                'update_time'=>time(),
                'award_img'=>$filename['oss-request-url'],
            ]);
            $content = $this->mkNoticeContent($user_id,'','获奖荣誉' ,2);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    /**
     * get获奖荣誉
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getAward(Request $request){
        $awardList = CommunityAward::get();
        foreach ($awardList as $award){
            $award['create_time'] =  $this->switchPreciseTime($award['create_time']);
            $award['update_time'] =  $this->switchPreciseTime($award['update_time']);
        }
       return $this->returnJson(self::SUCCESS,'成功' ,$awardList);
    }

    /**
     * get组长
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getLeader(Request $request){
        $leaderList = UserRole::where('role_id','=',2)
            ->join('users','users.id','=','user_roles.user_id')
            ->join('grades','grades.id','=','users.grade_id')
            ->join('introduces','introduces.user_id','=','user_roles.user_id')
            ->get(['user_roles.user_id as id','users.username','grades.grade','introduces.introduce','introduces.image','users.login_date']);
        foreach ($leaderList as $leader){
            $leader['login_date'] =  $this->switchPreciseTime($leader['login_date']);
        }
        return $this->returnJson(self::SUCCESS,'成功' ,$leaderList);
    }
    public function getUnIntroduceLeader(Request $request){
        $leaderList = UserRole::where('role_id','=',2)
            ->join('users','users.id','=','user_roles.user_id')
            ->get(['user_roles.user_id as value','users.username as label']);

        $list =array();
        foreach ($leaderList as $leader){
            if (Introduce::where('user_id','=',$leader['value'])->count()==0){
                array_push($list,$leader);
            }
        }
        return $this->returnJson(self::SUCCESS,'成功' ,$list);
    }
    public function getUnIntroduceQrcode(Request $request){
        $gradeList = Grade::get(['id as value','grade as label']);

        $list =array();
        foreach ($gradeList as $leader){
            if (CommunityIntroduce::where('grade_id','=',$leader['value'])->count()==0){
                array_push($list,$leader);
            }
        }
        return $this->returnJson(self::SUCCESS,'成功' ,$list);
    }
    /**
     * 修改组长介绍
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function  updateLeader(Request $request){
        $id = $request->input('id');
        if (Introduce::where('user_id','=',$id)->count()==0){
            return $this->returnJson(self::FIELD_ERROR,'无此人员');
        }

        $introduce = $request->input('introduce');
        $file = $request->file('img');
        $updateList =array();
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
            if ($file){
                //获取文件后缀
                $suffix = $file->getClientOriginalExtension();

                //判断文件后缀
                $rule = ['jpg', 'png', 'gif','jpeg'];
                if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

                //判断文件大小
                $fileSize = $file->getSize();
                if ($fileSize > 10 * 1024 * 1024){
                    return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
                }
                $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
                if (!$filename = $this->uploadOss('wdad/introduce/award'  , $fileUrl, $file->getRealPath())){
                    return $this->returnJson(self::ERROR,'失败');
                }
                $updateList['image'] = $filename['oss-request-url'];
            }

            if (isset($introduce)){
                $updateList['introduce'] = $introduce;
            }

            Introduce::where('user_id','=',$id)->update($updateList);
            $content = $this->mkNoticeContent($user_id,'','人员介绍' ,4);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    public function  createLeader(Request $request){
        $leader_id = $request->input('leader_id');
        $introduce = $request->input('introduce');
        $file = $request->file('img');
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
            if ($file){
                //获取文件后缀
                $suffix = $file->getClientOriginalExtension();

                //判断文件后缀
                $rule = ['jpg', 'png', 'gif','jpeg'];
                if (!in_array($suffix, $rule)) return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件格式必需为jpg/png/gif');

                //判断文件大小
                $fileSize = $file->getSize();
                if ($fileSize > 10 * 1024 * 1024){
                    return $this->returnJson(BaseController::FIELD_ERROR, '上传的文件必须在10m以内');
                }
                $fileUrl = md5(time() . $file->getClientOriginalName()) . '.' . $suffix;
                if (!$filename = $this->uploadOss('wdad/introduce/award'  , $fileUrl, $file->getRealPath())){
                    return $this->returnJson(self::ERROR,'失败');
                }
            }

            Introduce::insert([
                'image'=>$filename['oss-request-url'],
                'introduce'=>$introduce,
                'user_id'=>$leader_id,
            ]);
            $content = $this->mkNoticeContent($user_id,'','人员介绍' ,2);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    public function  deleteLeader(Request $request){
        $id = $request->input('id');
        if (Introduce::where('user_id','=',$id)->count()==0){
            return $this->returnJson(self::FIELD_ERROR,'无此人员');
        }
        $user_id =$request->userId;
        //创建启动事务
        DB::beginTransaction();
        try {
            Introduce::where('user_id','=',$id)->delete();
            $content = $this->mkNoticeContent($user_id,'','人员介绍' ,3);
            $this->creatNotice(2,$user_id,$content,true);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'服务器错误，请稍后从试',$e);
        }
        return $this->returnJson(self::SUCCESS,'成功' );
    }

    /**
     * 添加用户
     * @param Request $request
     * @param UserValidator $userValidator
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function creatUser(Request $request,UserValidator $userValidator){
        $params = [
            'username' => $request->input('name'),
        'email' => $request->input('email',''),
        'phone' => $request->input('phone'),
        'password'=> $request->input('password'),
        'grade_id' => $request->input('grade_id'),
        'introduce' => $request->input('introduce'),
        'role' => $request->input('role')
        ];

        if(empty($params['introduce'] ) )$params['introduce'] = '暂无';

        if (User::where('phone' ,'=',$params['phone'])->count() !=0) return$this->returnJson(self::DATA_NOTFOUND,'手机号码或邮箱已存在' );
        if (User::where('username','=',$params['username'])->count() !=0) return$this->returnJson(self::DATA_NOTFOUND,'用户名已存在' );
        $first = 1 ;
        if(empty($params['phone'] ) ){
            $params['phone'] = ' ';
            $first = 2;
        }

        if (!$userValidator->setScene('createUser')->check($params)){
            return $this->returnJson(BaseController::FIELD_ERROR, $userValidator->getError());
        }
           //创建启动事务
        DB::beginTransaction();
        try {
            $user_id= User::insertGetId([
                'username'=>$params['username'],
                'email'=>$params['email'],
                'phone'=>$params['phone'],
                'grade_id'=>$params['grade_id'],
                'introduce'=>$params['introduce'],
                'password'=>md5($params['password']),
                'create_time' => time(),
                'is_first' => $first
            ]);

            UserRole::insert([
                'user_id'=>$user_id,
                'role_id' => $params['role']
            ]);


            $admin_id = $request->userId;
            $content = $this->mkNoticeContent($admin_id,'','用户'."\t". $params['username'],2);
            $this->creatNotice(1,$admin_id,$content);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(self::DATA_NOTFOUND,'用户可能有冲突' );
        }
        return $this->returnJson(self::SUCCESS,'成功');


    }

    /**
     * 获取所有用户信息
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */

    public function getUserInfo(Request $request){
        $userInfo = User:: join('grades','grades.id','=','users.grade_id')
            ->join('user_roles','user_roles.user_id','=','users.id')
            ->join('roles','roles.id','=','user_roles.role_id');

        //获取所有tolken
        $redis_keys = Redis::keys('wdad.*');
        $token_id= array();
        foreach($redis_keys as $key){
            $redis_key = explode("_",$key);
            array_push($token_id,json_decode(Redis::get($redis_key[count($redis_key)-1]),true)['id']);
        }

        $userInfo =$userInfo->get(['users.id','users.username','users.email','users.phone','users.login_date','grades.grade','grades.id as grade_id','roles.name as position','roles.id as role_id']);
        foreach ($userInfo as $key){
            $key['login_date'] = $this->switchTime($key['login_date']);
            $key['isLogin']= 0;
            if (in_array($key['id'],$token_id)){
                $key['isLogin']= 1;
            }
        }

        return $this->returnJson(BaseController::SUCCESS,"成功",$userInfo);
    }

    /**
     * 塞选用户
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function screenUser(Request $request){
        $params = $request->only(['search','role_id','grade_id']);

        $params['is_login'] = $request->input('is_login','');
        $userInfo = User:: join('grades','grades.id','=','users.grade_id')
            ->join('user_roles','user_roles.user_id','=','users.id')
            ->join('roles','roles.id','=','user_roles.role_id');

        if (isset($params['search'])){
            $userInfo =$userInfo->where("user.username",'like','%' . $params['search'] .'%');
        }
        if ($params['grade_id'] != 0){
            $userInfo =$userInfo->where("grades.id",'=',$params['grade_id']);
        }
        if ($params['role_id'] !=0){
            $userInfo =$userInfo->where("roles.id",'=',$params['role_id']);
        }

        //获取所有tolken
        $redis_keys = Redis::keys('wdad.*');
        $token_id= array();
        foreach($redis_keys as $key){
            $redis_key = explode("_",$key);
            array_push($token_id,json_decode(Redis::get($redis_key[count($redis_key)-1]),true)['id']);
        }

        $userInfo =$userInfo->get(['users.id','users.username','users.email','users.phone','users.login_date','grades.grade','grades.id as grade_id','roles.name as position','roles.id as role_id']);

        if($params['is_login'] != null){
            $list = array();
            foreach ($userInfo as $key){
                $key['login_date'] = $this->switchTime($key['login_date']);
                $key['isLogin']= 0;
                if (in_array($key['id'],$token_id)){
                    $key['isLogin']= 1;
                }
                if ($key['isLogin'] == $params['is_login']){
                    array_push($list,$key);
                }
            }
            return $this->returnJson(BaseController::SUCCESS,"成功",$list);
        }

        foreach ($userInfo as $key){
            $key['login_date'] = $this->switchTime($key['login_date']);
            $key['isLogin']= 0;
            if (in_array($key['id'],$token_id)){
                $key['isLogin']= 1;
            }
        }

        return $this->returnJson(BaseController::SUCCESS,"成功",$userInfo);
    }

    /**
     * 修改用户信息
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function updateUserInfo(Request $request){
        $admin_id = $request->userId;

        $username = $request->input('username');
        $user_id = $request->input('user_id');
        $grade_id = $request->input('grade_id');
        $roles_id = $request->input('roles_id');
        $phone = $request->input('phone');

        //创建启动事务
        DB::beginTransaction();
        try {
            $update_array = array();
            $userinfo = User::where('id','=',$user_id)->first();
            if (isset($username) && $username!=$userinfo['username']){
                $update_array['username']=$username;
                $content = $this->mkNoticeContent($admin_id,$user_id,"改名为" . $username);
                $this->creatNotice(1,$user_id,$content );
            }

            if (isset($grade_id)&& $grade_id!=$userinfo['grade_id']){
                $update_array['grade_id']=$grade_id;
                $content = $this->mkNoticeContent($admin_id,$user_id,"修改了年级");
                $this->creatNotice(1,$user_id,$content);
            }

            if (isset($phone)&& $phone!=$userinfo['phone']){
                $update_array['phone']=$phone;
                $content = $this->mkNoticeContent($admin_id,$user_id,"修改了联系方式");
                $this->creatNotice(1,$user_id,$content);
            }



            $roles = UserRole::where('user_id','=',$user_id)->pluck('role_id');
            if (isset($roles_id)&& $roles_id!=$roles[0]){
                UserRole::where('user_id','=',$user_id)->update(['role_id'=>$roles_id]);
                $roles = Role::where('id','=',$roles_id)->pluck('name')[0];
                $content = $this->mkNoticeContent($admin_id,$user_id,"改为了\t" . $roles);
                $this->creatNotice(1,$user_id,$content);
            }

            if(!empty($update_array)){
                User::where('id','=',$user_id)->update($update_array);
            }

            Redis::del('userInfo');

            //获取所有tolken
            $redis_keys = Redis::keys('wdad.*');

            foreach($redis_keys as $key){
                $redis_key = explode("_",$key);
                if($user_id == json_decode(Redis::get($redis_key[count($redis_key)-1]),true)['id']){
                    //删除用户
                    Redis::del($redis_key[count($redis_key)-1]);
                }
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(BaseController::ERROR,"失败",$e);
        }
        return $this->returnJson(BaseController::SUCCESS,"成功");

    }

    /**
     * 删除用户
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function delUser(Request $request){
        $admin_id = $request->userId;
        $user_id = $request->input('user_id');
        //创建启动事务
        DB::beginTransaction();
        try {
            $content = $this->mkNoticeContent($admin_id,$user_id,"赶尽杀绝了");

            if (!isset($user_id))$this->returnJson(BaseController::FIELD_ERROR,"数据不能为空");

           User::where('id','=',$user_id)->delete();

            //获取所有tolken
            $redis_keys = Redis::keys('wdad.*');

            foreach($redis_keys as $key){
                $redis_key = explode("_",$key);
                if (json_decode(Redis::get($redis_key[count($redis_key)-1]),true)['id'] == $user_id){
                    Redis::del($redis_key[count($redis_key)-1]);
                }
            }

            $this->creatNotice(1,$user_id,$content);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnJson(BaseController::ERROR,"失败",$e);
        }

        return $this->returnJson(BaseController::SUCCESS,"成功");
    }
    /**
     * 批量删除用户
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function batchDelUser(Request $request){
        $admin_id = $request->userId;
        $user_list = $request->input('user_id');
        if (!is_array($user_list)) $user_list = explode(',',$user_list);
        //创建启动事务
        DB::beginTransaction();
        try {
            foreach ($user_list as $user_id){
                $content = $this->mkNoticeContent($admin_id,$user_id,"赶尽杀绝了");

                if (!isset($user_id))$this->returnJson(BaseController::FIELD_ERROR,"数据不能为空");

                User::where('id','=',$user_id)->delete();

                //获取所有tolken
                $redis_keys = Redis::keys('wdad.*');

                foreach($redis_keys as $key){
                    $redis_key = explode("_",$key);
                    if (json_decode(Redis::get($redis_key[count($redis_key)-1]),true)['id'] == $user_id){
                        Redis::del($redis_key[count($redis_key)-1]);
                    }
                }

                $this->creatNotice(1,$user_id,$content);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e;
        }

        return $this->returnJson(BaseController::SUCCESS,"成功");
    }
    /**
     * 重置用户
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function resetUser(Request $request){
        $user_id = $request->input('id');

        //重置用户
        User::where('id', $user_id)->update([
            'password'  =>  md5(12345678),
            'phone'     =>  null,
            'is_first'  =>  1
        ]);

        $admin_id = $request->userId;
        $content = $this->mkNoticeContent($admin_id,$user_id,"重置了");
        $this->creatNotice(1,$user_id,$content);

        return $this->returnJson(BaseController::SUCCESS, '用户重置成功');
    }

    /**
     * get所有年级
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public  function getGrades(){
        return $this->returnJson(self::SUCCESS,'成功',Grade::get(['id as value','grade as label']));
    }

    /**
     * 添加年级
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function creatGrades(Request $request){
        $grade = $request->input('grade');
        if (!Grade::insert(['grade' => $grade])) return $this->returnJson(self::ERROR,'添加失败');
        return $this->returnJson(self::SUCCESS,'成功');
    }

    /**
     * get所有职位
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public  function getRoles(){

        return $this->returnJson(self::SUCCESS,'成功',Role::get(['id as value','name as label']));
    }

    public function  batchCreateUser(Request  $request,Excel  $excel){
        $file = $request->file('file');

        try {
           $excel->import(new CompanyUserImport, $file);
        }catch (\Exception $e){
            return $e;
        }
        return  $this->returnJson(self::SUCCESS,'成功');
    }
}
